import { Request, Response } from 'express';
import { TrafficModel } from '../models/traffic.model';
import { ExcelService } from '../services/excel.service';
import { AppError } from '../middlewares/errorHandler';
import fs from 'fs';

export class TrafficController {
  private trafficModel: TrafficModel;
  private excelService: ExcelService;

  constructor() {
    this.trafficModel = new TrafficModel();
    this.excelService = new ExcelService();
  }

  // 获取流量数据列表
  getTrafficList = async (req: Request, res: Response) => {
    const { page = 1, pageSize = 10, startDate, endDate, source, medium, campaign } = req.query;

    const conditions: any = {};
    if (source) conditions.source = source;
    if (medium) conditions.medium = medium;
    if (campaign) conditions.campaign = campaign;
    if (startDate && endDate) {
      conditions.date = { between: [startDate, endDate] };
    }

    const result = await this.trafficModel.findWithPagination(
      Number(page),
      Number(pageSize),
      conditions
    );

    res.json(result);
  };

  // 获取流量数据汇总
  getTrafficSummary = async (req: Request, res: Response) => {
    const { startDate, endDate } = req.query;

    if (!startDate || !endDate) {
      throw new AppError('开始日期和结束日期是必需的', 400);
    }

    const summary = await this.trafficModel.getTrafficSummary(
      startDate as string,
      endDate as string
    );

    res.json(summary);
  };

  // 获取流量来源分布
  getSourceDistribution = async (req: Request, res: Response) => {
    const { startDate, endDate } = req.query;

    if (!startDate || !endDate) {
      throw new AppError('开始日期和结束日期是必需的', 400);
    }

    const distribution = await this.trafficModel.getTrafficSourceDistribution(
      startDate as string,
      endDate as string
    );

    res.json(distribution);
  };

  // 获取转化率趋势
  getConversionTrend = async (req: Request, res: Response) => {
    const { startDate, endDate } = req.query;

    if (!startDate || !endDate) {
      throw new AppError('开始日期和结束日期是必需的', 400);
    }

    const trend = await this.trafficModel.getConversionTrend(
      startDate as string,
      endDate as string
    );

    res.json(trend);
  };

  // 导入Excel数据
  importExcel = async (req: Request, res: Response) => {
    if (!req.file) {
      throw new AppError('请上传文件', 400);
    }

    try {
      const result = await this.excelService.importData(req.file.path);
      
      // 删除临时文件
      fs.unlinkSync(req.file.path);
      
      res.json({
        message: '数据导入成功',
        ...result
      });
    } catch (error) {
      // 删除临时文件
      if (req.file) {
        fs.unlinkSync(req.file.path);
      }
      throw error;
    }
  };

  // 导出数据
  exportData = async (req: Request, res: Response) => {
    const { startDate, endDate, type = 'xlsx' } = req.query;

    if (!startDate || !endDate) {
      throw new AppError('开始日期和结束日期是必需的', 400);
    }

    if (type !== 'xlsx' && type !== 'csv') {
      throw new AppError('不支持的导出格式', 400);
    }

    // 获取数据
    const data = await this.trafficModel.findAll({
      date: { between: [startDate, endDate] }
    });

    // 导出数据
    const { buffer, filename } = await this.excelService.exportData(data, type);

    // 设置响应头
    res.setHeader('Content-Type', type === 'xlsx' 
      ? 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      : 'text/csv');
    res.setHeader('Content-Disposition', `attachment; filename=${filename}`);

    // 发送文件
    res.send(buffer);
  };

  // 创建流量数据
  createTrafficData = async (req: Request, res: Response) => {
    const data = req.body;

    if (!Array.isArray(data)) {
      throw new AppError('数据格式错误', 400);
    }

    const result = await this.trafficModel.batchCreate(data);
    res.json(result);
  };

  // 更新流量数据
  updateTrafficData = async (req: Request, res: Response) => {
    const { id } = req.params;
    const data = req.body;

    const result = await this.trafficModel.update(id, data);
    res.json(result);
  };

  // 批量更新流量数据
  batchUpdateTrafficData = async (req: Request, res: Response) => {
    const { ids, data } = req.body;

    if (!Array.isArray(ids) || !data) {
      throw new AppError('数据格式错误', 400);
    }

    const results = await Promise.all(
      ids.map(id => this.trafficModel.update(id, data))
    );

    res.json({
      message: '批量更新成功',
      results
    });
  };

  // 删除流量数据
  deleteTrafficData = async (req: Request, res: Response) => {
    const { id } = req.params;

    const result = await this.trafficModel.delete(id);
    res.json(result);
  };

  // 批量删除流量数据
  batchDeleteTrafficData = async (req: Request, res: Response) => {
    const { ids } = req.body;

    if (!Array.isArray(ids)) {
      throw new AppError('数据格式错误', 400);
    }

    const results = await Promise.all(
      ids.map(id => this.trafficModel.delete(id))
    );

    res.json({
      message: '批量删除成功',
      results
    });
  };
} 